<template>
    <div class="goods_form_container" :style="containerStyle">
        <el-form ref="goodsForm" :model="formData" :rules="rules" label-width="80px"
                 @submit.native.prevent>
            <el-row>
                <el-col :span="24">
                    <div class="title_area">
                        <div class="title">基本信息</div>
                    </div>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="类目" prop="category_sid">
                        <custom-tree-select v-model="formData.category_sid" :select-props="categoryOption.selectOption"
                                            :tree-props="categoryOption.treeOption" :options="treeData"
                                            expand-all select-leaf :clearable="false"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="编号" prop="code">
                        <el-input v-model="formData.code" placeholder="请输入编号" :disabled="!isEditFlag" clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="formData.name" placeholder="请输入名称" :disabled="!isEditFlag" clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="规格" prop="spec">
                        <el-input v-model="formData.spec" placeholder="请输入规格" :disabled="!isEditFlag" clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="型号" prop="model">
                        <el-input v-model="formData.model" placeholder="请输入型号" :disabled="!isEditFlag" clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="简称" prop="short_name">
                        <el-input v-model="formData.short_name" placeholder="请输入简称" :disabled="!isEditFlag"
                                  clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="助记码" prop="search_code">
                        <el-input v-model="formData.search_code" placeholder="请输入助记码" :disabled="!isEditFlag"
                                  clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="16">
                    <el-form-item label="备注" prop="note_info">
                        <el-input type="textarea" v-model="formData.note_info" placeholder="请输入备注"
                                  :disabled="!isEditFlag" maxlength="200" :rows="1"
                                  show-word-limit clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="图标" prop="icon_file_sid">
                        <upload-cropper :options="uploadCropperOptions" :isEditFlag="isEditFlag"
                                        width="100px" height="100px" single
                                        :data="uploadCropperData" @success="uploadIconSuccess"/>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <div class="title_area">
                        <div class="title">单位与价格</div>
                        <vxe-toolbar ref="toolbarRef" custom size="mini">
                            <template v-slot:buttons>
                                <el-tooltip class="item" effect="dark" placement="top"
                                            content="点击后，根据单位关系自动计算所有辅助单位的价格">
                                    <el-button type="success" @click.stop="autoCalcPrice()">自动换算价格</el-button>
                                </el-tooltip>
                            </template>
                        </vxe-toolbar>
                    </div>
                </el-col>
                <el-col :span="24">
                    <vxe-table-template :options.sync="priceTableOptions" :data="goodsPriceList"/>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import provide from "@common/mixins/provide";

export default {
    extends: provide,
    name: "GoodsForm",
    components: {
        CustomTreeSelect: () => import("@common/components/custom/TreeSelect"),
        UploadCropper: () => import("@common/components/upload/UploadCropper"),
    },
    props: {
        row: {
            type: Object,
            default: null,
        },
        treeData: {
            type: Array,
            default: () => [],
        },
    },
    data() {
        const _this = this;
        return {
            formData: {},
            rules: {
                category_sid: [{required: true, message: '请选择类目', trigger: 'blur'}],
                code: [{required: true, message: '请输入编号', trigger: 'blur'}],
                name: [{required: true, message: '请输入名称', trigger: 'blur'}],
            },
            categoryOption: {
                selectOption: {
                    label: 'name',
                    placeholder: '请选择类目',
                    clearable: false,
                },
                treeOption: {
                    nodeKey: 'sid',
                    props: {
                        label: 'name',
                        children: 'children',
                    },
                },
            },
            uploadCropperOptions: {
                dialogOptions: {
                    title: "图片裁剪",
                    visible: true,
                    width: "200px",
                    height: "100px",
                },
                cropperOptions: {
                    autoCropWidth: 200, // 默认生成截图框宽度
                    autoCropHeight: 200, // 默认生成截图框高度
                    canScale: true,//
                    canMoveBox: true,
                    fixed: false,
                    fixedBox: true,
                },
                uploadOptions: {
                    // tip: '请裁剪200*200的图片',
                    associate_biz_table: 'jxc_goods',
                    associate_biz_field_tag: 'icon_file_sid',
                }
            },
            uploadCropperData: [],
            isEditFlag: true,
            unitList: [],
            defaultForBillList: [
                { label: '进货', value: 'j' },
                { label: '销货', value: 'x' },
                { label: '库存', value: 'c' },
            ],
            priceTableOptions: {
                ref: 'GoodsPriceTable',
                keepSource: true,
                editConfig: {
                    trigger: "click",
                    mode: "cell",
                    showStatus: true,
                },
                editRules: {
                    unit_name: [
                        {required: true, message: '请输入'},
                    ],
                    qty: [
                        {required: true, message: '请输入'},
                    ],
                },
                columns: [
                    {
                        label: '单位名称',
                        prop: 'unit_name',
                        align: 'center',
                        minWidth: 100,
                        editRender: {
                            name: "CustomSelect",
                            autoselect: true,
                            props: {
                                filterable: true,
                                clearable: true,
                                allowCreate: true,
                                dataMethod() {
                                    return _this.unitList;
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '单位关系',
                        prop: 'qty',
                        align: 'center',
                        minWidth: 100,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                integer: true,
                            },
                            events: {
                                change: _this.rewriteChangeRow,
                            },
                            filter(row) {
                                return row._index > 0;
                            },
                            formatter(row) {
                                if (_this.$utils.isNotEmpty(row.qty)) {
                                    return `<div style="display: flex;align-items: center;justify-content: flex-end;gap: 10px;padding: 0 10px;"><span>=</span><span>${row.qty}</span></div>`;
                                }
                                return '';
                            },
                        },
                    },
                    {
                        label: 'SKU条码',
                        prop: 'sku_code',
                        align: 'center',
                        minWidth: 90,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '设为单据默认单位',
                        prop: 'default_for_bill_list',
                        align: 'center',
                        minWidth: 130,
                        editRender: {
                            name: "CustomSelect",
                            props: {
                                multiple: true,
                                collapseTags: true,
                                filterable: true,
                                clearable: true,
                                dataMethod(row, column) {
                                    let skipList = [];
                                    const datas = _this.goodsPriceList.filter(item => item._index !== row._index);
                                    if (_this.$utils.isNotEmptyList(datas)) {
                                        datas.forEach(item => {
                                            skipList = skipList.concat(item.default_for_bill_list || []);
                                        });
                                    }
                                    return _this.defaultForBillList.filter(item => !skipList.includes(item.value));
                                },
                            },
                            formatter(row) {
                                const filters = _this.defaultForBillList.filter(item => row.default_for_bill_list.includes(item.value));
                                return filters.map(item => item.label).join('、');
                            },
                            events: {
                                change: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '采购价',
                        prop: 'buy_price',
                        align: 'center',
                        minWidth: 90,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '最低零售价',
                        prop: 'min_sale_price',
                        align: 'center',
                        minWidth: 100,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '零售价',
                        prop: 'sale_price',
                        align: 'center',
                        minWidth: 90,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '预设价格1',
                        prop: 'price1',
                        align: 'center',
                        minWidth: 90,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '预设价格2',
                        prop: 'price2',
                        align: 'center',
                        minWidth: 90,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '预设价格3',
                        prop: 'price3',
                        align: 'center',
                        minWidth: 90,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '长/cm',
                        prop: 'length_cm',
                        align: 'center',
                        minWidth: 80,
                        visible: true,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '宽/cm',
                        prop: 'width_cm',
                        align: 'center',
                        minWidth: 80,
                        visible: true,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '高/cm',
                        prop: 'height_cm',
                        align: 'center',
                        minWidth: 80,
                        visible: true,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                    {
                        label: '体积/cm³',
                        prop: 'volume_cm3',
                        align: 'center',
                        minWidth: 80,
                        visible: true,
                    },
                    {
                        label: '重量/g',
                        prop: 'weight_g',
                        align: 'center',
                        minWidth: 80,
                        visible: true,
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                    },
                ],
                operates: {
                    fixed: 'left',
                    list: [
                        {
                            id: "add1",
                            show: true,
                            tooltip: {
                                content: '插入',
                            },
                            svg: {
                                iconClass: 'icon-insert',
                            },
                            hidden(row) {
                                return row._index === 0;
                            },
                            method: (key, row, index) => {
                                _this.handleAddRow(row, -1);
                            },
                        },
                        {
                            id: 'add2',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '追加',
                            },
                            svg: {
                                iconClass: 'icon-append',
                            },
                            method: (index, row) => {
                                _this.handleAddRow(row, 1);
                            }
                        },
                        {
                            id: "edit",
                            icon: "fa fa-trash-o",
                            show: true,
                            type: "danger",
                            tooltip: {
                                content: "删除",
                            },
                            hidden(row) {
                                return row._index === 0;
                            },
                            method: (key, row, index) => {
                                let dataList = _this.goodsPriceList.map(item => $.extend({}, item));
                                dataList = dataList.filter(item => item._index !== row._index);
                                _this.goodsPriceList = _this.resetIndex(dataList);
                            },
                        },
                    ],
                },
                minHeight: 270,
                getMaxHeight() {
                    return 270;
                },
            },
            initGoodsPriceData: {
                unit_name: null,
                qty: null,
                sku_code: null,
                default_for_bill_list: [],
                buy_price: null,
                min_sale_price: null,
                sale_price: null,
                price1: null,
                price2: null,
                price3: null,
                weight_g: null,
                length_cm: null,
                width_cm: null,
                height_cm: null,
            },
            goodsPriceList: [],
        }
    },
    computed: {
        containerStyle() {
            let height = $(this.getActiveTabsContainer()).height() * 0.8 - 60;
            return {
                maxHeight: `${height}px`,
            };
        },
        goodsPriceTableRef() {
            return this[this.priceTableOptions.ref];
        },
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            if (!_this.row) {
                return;
            }
            await _this.initBaseUnitList();
            await _this.initData(_this.row);
            _this.uploadCropperData = [];
            if (_this.$utils.isNotEmpty(_this.formData.icon_file_sid)) {
                _this.uploadCropperData = [{file_sid: _this.formData.icon_file_sid}];
            }
            _this.$nextTick(() => {
                if (this.goodsPriceTableRef && this.$refs.toolbarRef) {
                    this.goodsPriceTableRef.connect(this.$refs.toolbarRef);
                }
            });
        },
        initBaseUnitList() {
            const _this = this;
            return _this.fetchDataNoCatch(_this.$api.API_FindBaseUnits, {
                state: 1,
                nopage: '1',
            }).then(res => {
                _this.unitList = (res.data || []).map(item => {
                    return {
                        label: item.name,
                        value: item.name,
                    };
                });
            });
        },
        initData(row, copy) {
            const _this = this;
            if (_this.$utils.isEmpty(row.sid)) {
                _this.handleAddRow(null, 1);
                _this.formData = $.extend({}, _this.row);
                return;
            }
            const queryData = {
                sid: row.sid,
            };
            if (copy) {
                queryData.copy = '1';
            }
            return _this.fetchDataNoCatch(_this.$api.API_GetJxcGoodsBySid, queryData).then(res => {
                const resData = res.data || {};
                _this.formData = $.extend({}, resData);
                const goodsPriceList = (resData.price_list || []).map(item => $.extend({}, _this.initGoodsPriceData, item));
                _this.goodsPriceList = _this.resetIndex(goodsPriceList);
            });
        },
        handleAddRow(row, state = 1) {
            const _this = this;
            let dataList = _this.goodsPriceList.map(item => $.extend({}, item));
            let addData = $.extend({}, _this.initGoodsPriceData);
            if (row === null) {
                addData.qty = 1;
            }
            if (row && state <= 0) {
                let index = _this.goodsPriceList.findIndex(item => item._index === row._index);
                if (index !== -1) {
                    if (index === 0) {
                        dataList.unshift(addData);
                    } else {
                        dataList.splice(index, 0, addData);
                    }
                } else {
                    dataList.push(addData);
                }
            } else {
                dataList.push(addData);
            }
            _this.goodsPriceList = _this.resetIndex(dataList);
        },
        rewriteChangeRow({row, column}) {
            const _this = this;
            column = Object.assign({}, column, column.params)
            // 手动限制控制数字位数
            if (column.editRender && column.editRender.double) {
                _this.$set(row, column.prop, _this.$XEUtils.DoubleInput(row[column.prop], column.editRender.double));
            }
            if (column.editRender && column.editRender.integer) {
                _this.$set(row, column.prop, _this.$XEUtils.IntInput(row[column.prop]));
            }
        },
        uploadIconSuccess(data) {
            const _this = this;
            let icon_file_sid = '';
            if (_this.$utils.isNotEmptyList(data)) {
                icon_file_sid = data[0].sid;
            }
            _this.formData = $.extend({}, _this.formData, {
                icon_file_sid,
            });
        },
        autoCalcPrice() {
            const _this = this;
            if (_this.goodsPriceList.length === 1) {
                return;
            }
            const basePrice = _this.goodsPriceList.find(item => item.qty === 1);
            const dataList = _this.goodsPriceList.map(item => {
                const obj = $.extend({}, item);
                if (item._index > 0 && _this.$utils.isNotEmpty(item.qty)) {
                    if (_this.$utils.isNotEmpty(basePrice.buy_price)) {
                        obj.buy_price = Number(_this.$utils.accMul2Fixed(basePrice.buy_price, item.qty, 4));
                    }
                    if (_this.$utils.isNotEmpty(basePrice.min_sale_price)) {
                        obj.min_sale_price = Number(_this.$utils.accMul2Fixed(basePrice.min_sale_price, item.qty, 4));
                    }
                    if (_this.$utils.isNotEmpty(basePrice.sale_price)) {
                        obj.sale_price = Number(_this.$utils.accMul2Fixed(basePrice.sale_price, item.qty, 4));
                    }
                    if (_this.$utils.isNotEmpty(basePrice.price1)) {
                        obj.price1 = Number(_this.$utils.accMul2Fixed(basePrice.price1, item.qty, 4));
                    }
                    if (_this.$utils.isNotEmpty(basePrice.price2)) {
                        obj.price2 = Number(_this.$utils.accMul2Fixed(basePrice.price2, item.qty, 4));
                    }
                    if (_this.$utils.isNotEmpty(basePrice.price3)) {
                        obj.price3 = Number(_this.$utils.accMul2Fixed(basePrice.price3, item.qty, 4));
                    }
                }
                return obj;
            });
            _this.goodsPriceList = _this.resetIndex(dataList);
        },
        async confirm(operate = 0) {
            const _this = this;
            let valid = await _this.validateForm('goodsForm');
            if (!valid) {
                return false;
            }
            if (_this.goodsPriceTableRef) {
                const errMap = await _this.goodsPriceTableRef.validate(true);
                if (errMap) {
                    return false;
                }
            }
            let subData = $.extend({}, _this.formData);
            subData.price_list = _this.goodsPriceList.map(item => {
                const obj = $.extend({}, item);
                obj.sn = item._index + 1;
                obj.default_for_bills = JSON.stringify(item.default_for_bill_list);
                delete obj._index;
                delete obj.default_for_bill_list;
                return obj;
            });
            return _this.fetchData(_this.$api.API_SaveJxcGoods, subData).then(res => {
                const resData = res.data || {};
                _this.$message.success('保存成功！');
                if (operate === 1) {
                    // 保存并新增
                    _this.formData = {
                        category_sid: subData.category_sid,
                    };
                    _this.goodsPriceList = [];
                    _this.handleAddRow(null, 1);
                } else if (operate === 2) {
                    // 保存并复制
                    _this.initData(resData, true);
                }
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.goods_form_container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    overflow-y: auto;

    /deep/ .title_area {
        margin-bottom: 10px;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 20px;

        .title {
            font-size: 16px;
            font-weight: bold;
            padding: 5px 0 5px 20px;

            &:before {
                content: '';
                width: 2px;
                height: 100%;
                position: absolute;
                left: 10px;
                top: 0;
                background-color: #66b1ff;
            }
        }

        .vxe-toolbar {
            padding: 0;
            flex: 1;
        }
    }
}
</style>
